package pinboard.dataLayer.net;

abstract class Runner {

    public Runner() {

    }

    Thread worker = null;
    volatile boolean doWhile = false;

    private void init() {
        worker = new Thread(new Runnable() {
            @Override
            public void run() {
                while (doWhile) {
                    long sleep = loopRun();
                    try {
                        Thread.sleep(sleep);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public synchronized void start() {
        start(null);
    }

    public synchronized void start(String name) {
        if (!doWhile) {
            doWhile = true;
            init();
            if (name != null) {
                worker.setName(name);
            }
            worker.start();
        }
    }

    public synchronized void stop() {
        if (doWhile) {
            doWhile = false;
            if (worker != null) {
                worker.interrupt();
            }
        }
    }

    protected abstract long loopRun();

}
